#!/usr/bin/env python

import os
import urllib2
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

def search(metadata):
	# Build a GET request
	url = "http://www.threatexpert.com/report.aspx?md5=" + metadata['md5']
	request = urllib2.Request(url)
	
	# Make the request and capture the response
	try:
		response = urllib2.urlopen(request)
	except URLError, e:
		print "Error: " + e.strerror
		print "Searching for existing ThreatExpert reports failed..."
		return False
	
	result = response.geturl()
	
	# ThreatExpert stays on report.aspx if found
	# and redirects to reports.aspx if not found
	if "report.aspx" in result:
		print "ThreatExpert: Found existing report"
		metadata['ThreatExpert'] = response.geturl()
		return True
	else:
		#print "ThreatExpert has not seen this file before"
		return False

def submit(filepath, from_addr):
	# Validate filesize is less than 5MB
	if os.stat(filepath).st_size >= 5242880:
		print "Error: File is too large"
		return False
	
	try:
		filehandle = open(filepath, "rb")
	except IOError, e:
		print "Error: " + e.strerror
		print "Could not open " + filepath + "for reading"
		sys.exit(1)
	
	# Needed for poster module
	register_openers()
	
	# Set request headers and parameters
	url = "http://www.threatexpert.com/client_submission.aspx"
	params = { "email" : "mailto:" + from_addr,
				"tems_submission" : filehandle }
	
	# Multipart encode the parameters			
	datagen, headers = multipart_encode(params)
	request = urllib2.Request(url, datagen, headers)
	#request.set_proxy("127.0.0.1:8080", "http")
	
	# Make the request
	try:
		response = urllib2.urlopen(request)
		result = response.read()
	except urllib2.URLError, e:
		print e.reason
		print "Submitting to ThreatExpert failed..."

	filehandle.close()

	# Verify successful submission response
	if (response.code == 200 and result.find("Sample successfully uploaded") != -1):
		print "ThreatExpert: Check your email for results"
		return True;
	else:
		print "ThreatExpert: Malware submission FAILED"
		return False;
		
if __name__ == "__main__":
	import sys
	
	submit(sys.argv[1], "malware@cryptocity.net")
